import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import { Button, ConfigProvider, Dropdown, Space, Tag, Avatar, Tooltip, Popconfirm } from 'antd';
import { useRef, useState } from 'react';
import _ from 'lodash';
import { UserOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { Ajax } from '@/api/api';
import { baseURL } from '@/api/request';
import { useMobxStore } from '@/mobx/store';
import { observer } from 'mobx-react';
import ExportExcle from '@/components/ExportExcle';
import UpdateUserForm from './UpdateUserForm';



type GithubIssueItem = {
    url: string;
    id: number;
    number: number;
    title: string;
    labels: {
        name: string;
        color: string;
    }[];
    state: string;
    comments: number;
    created_at: string;
    updated_at: string;
    closed_at?: string;
};


const UserList = () => {

    const [tableData, setTableData] = useState<any>([])
    const actionRef = useRef<ActionType>();
    const {
        MyData: {
            roleList
        }
    } = useMobxStore()
    const [open, setOpen] = useState<boolean>(false)
    const [updateData, setUpdateData] = useState<any>({})


    const columns: ProColumns<GithubIssueItem>[] = [


        {
            dataIndex: 'index',
            valueType: 'indexBorder',
            width: 48,
            title: "序号"
        },
        {
            title: '用户名称',
            dataIndex: 'username',
            ellipsis: true,
        },
        {
            title: '手机号码',
            dataIndex: 'phone',
            filters: true,
            onFilter: true,
            ellipsis: true,
            render: (_, record: any) => {
                return (
                    <span>
                        {record.phone}
                    </span>
                )
            }
        },
        {
            title: '头像',
            dataIndex: 'avatar',
            search: false,
            renderFormItem: (_, { defaultRender }) => {
                return defaultRender(_);
            },
            render: (_, record: any) => (
                <Space>
                    {
                        record.avatar ?
                            <Avatar size={30} src={record.avatar?.replace(/public/, baseURL)} />
                            :
                            <Avatar size={30} icon={<UserOutlined />} style={{ background: '#b5b5b5' }} />
                    }
                </Space>
            ),
        },
        {
            title: '角色',
            dataIndex: 'role',
            filters: true,
            onFilter: true,
            ellipsis: true,
            valueType: 'select',
            render: (scope, record: any) => {
                return (

                    roleList.size > 0 && <Tag color={_.find(roleList.toJS(), (item: any) => item.value == record.role).color} >
                        {_.find(roleList.toJS(), (item: any) => item.value == record.role).label}
                    </Tag>
                )
            },
            valueEnum: {

            },
            request: async () => {
                let res = await Ajax.getrolelist() as any;
                return res.result;
            }
        },
        {
            title: '创建时间',
            key: 'time',
            dataIndex: 'time',
            valueType: 'date',
            sorter: true,
            search: false,
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (text, record: any, _, action) => [
                <Popconfirm
                    key='delete'
                    title="Are you sure to delete this user?"
                    onConfirm={async () => {
                        let res = await Ajax.deleteuser({
                            _id: record._id
                        }) as any;
                        if (res.code == 200) {
                            actionRef.current?.reload()
                        }
                    }}
                    okText="Yes"
                    cancelText="No"
                >
                    <Button
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => {

                        }}
                        size="small"
                    />
                </Popconfirm>,

                <Tooltip title='修改用户信息' key='update'>
                    <Button
                        type="primary"
                        icon={<EditOutlined />}
                        size="small"
                        onClick={
                            () => {
                                setOpen(true)
                                setUpdateData({ ...record })
                            }
                        }
                    />

                </Tooltip>
            ],
        },
    ];

    return (
        <ConfigProvider >

            <UpdateUserForm updateData={updateData} open={open} setOpen={setOpen} actionRef={actionRef} />
            <ProTable<GithubIssueItem>
                columns={columns}
                actionRef={actionRef}
                cardBordered
                request={async (params = {}, sort, filter) => {
                    console.log(sort, filter);
                    let res = await Ajax.getallusers(params) as any  // params 搜索参数  
                    if (res.code == 200) {
                        setTableData(res.result)
                        return {
                            data: res.result,
                            success: true
                        }
                    } else {
                        return {
                            data: [],
                            success: false
                        }
                    }
                }}
                editable={{
                    type: 'multiple',
                }}
                columnsState={{
                    persistenceKey: 'pro-table-singe-demos',
                    persistenceType: 'localStorage',
                    onChange(value) {
                        console.log('value: ', value);
                    },
                }}
                rowKey="id"
                search={{
                    labelWidth: 'auto',
                }}
                options={{
                    setting: {
                        listsHeight: 400,
                    },
                }}
                form={{
                    syncToUrl: (values, type) => {
                        if (type === 'get') {
                            return {
                                ...values,
                                created_at: [values.startTime, values.endTime],
                            };
                        }
                        return values;
                    },
                }}
                pagination={{
                    pageSize: 5,
                    onChange: (page) => console.log(page),
                }}
                dateFormatter="string"
                headerTitle="用户详细数据列表"
                toolBarRender={() => [
                    <ExportExcle key='export' data={tableData} />,
                    <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => history.push('/main/user/add')}>
                        新建
                    </Button>,
                    <Dropdown
                        key="menu"
                        menu={{
                            items: [
                                {
                                    label: '1st item',
                                    key: '11',
                                },
                                {
                                    label: '2nd item',
                                    key: '12',
                                },
                                {
                                    label: '3rd item',
                                    key: '13',
                                },
                            ],
                        }}
                    >
                        <Button>
                            <EllipsisOutlined />
                        </Button>
                    </Dropdown>,
                ]}
            />
        </ConfigProvider>
    );
};


export default observer(UserList)